package zhh.tangbao.machine.manager;

import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import zhh.tangbao.machine.pojo.PreConnectionVerificationMachine;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * <p>
 *     描述
 * </p>
 * @author 粥灰灰
 * <p>2023/3/25</p>
 */

@Component
public class ConnectionManager {

    @Value("${custom.socket.vCodeExpireTime}")
    private long vCodeExpireTime;

    private Map<String, PreConnectionVerificationMachine> connectionVerificationCode;

    private Timer clearer;

    @PostConstruct
    void init() {
        this.connectionVerificationCode = Maps.newConcurrentMap();
        this.clearer = new Timer();
    }

    /**
     * 通过调用接口设置socket心跳服务的预连接验证码
     * @param vcode 本次申请连接的验证码
     * @param acode 申请连接的机器激活码
     */
    public void setPreConnectionVerificationCode(String vcode, String machineId,  String acode) {
        connectionVerificationCode.put(vcode, new PreConnectionVerificationMachine(machineId, acode));
        clearer.schedule(new TimerTask() {
            @Override
            public void run() {
                connectionVerificationCode.remove(vcode);
            }
        }, vCodeExpireTime);
    }

    public void removeVCode(String vcode) {
        connectionVerificationCode.remove(vcode);
    }

    public PreConnectionVerificationMachine getACode(String vcode) {
        return connectionVerificationCode.get(vcode);
    }

}
